<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            返修复检确认
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:60px;">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">当前操作人:</div>
                    <input type="text" class="aui-input" id="empName" disabled style="width: 80%;" />
                    <i class="aui-btn aui-btn-info aui-input-addon aui-iconfont" onclick="takeQuitPostClick()">上岗</i>
                </div>
            </li>


            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">产品条码:</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="请扫描产品条码" id="barcode" value="" onclick="getIdSelector();">
                    </div>
                </div>
            </li>
            <div class="aui-content" style="background-color: #ffffff">
                <ul class="aui-list-view aui-grid-view" id="imgslist">
                    <li class="aui-list-view-cell aui-img aui-col-xs-4" id="addpic" onclick="imgClick()">
                        <img class="aui-img-object" src="../image/add.jpg">
                    </li>
                </ul>
            </div>

        </ul>
        <div style="width:100%;margin-top:2%;"></div>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="confirm()">确认</div>

        <div style="width:100%;margin-top:2%;"></div>

        <ul class="ui-selectee" id="tbodyHtmlS" style="margin-bottom:12%;">

        </ul>

    </div>
    <footer class="aui-bar aui-bar-tab" id="footer">
        <div class="aui-bar-tab-item" tapmode id="scan" onclick="doScan()">
            <i class="aui-iconfont aui-icon-scan aui-text-epblue" style="font-size: 1.8rem"></i>
        </div>
    </footer>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript">

    var equipUniqueId = "";   //设备唯一号
    var workCenterCode = "";  //生产线编码
    var workCellCode = "";    //工位编码
    var opCode = "";          //工序编码
    var ruleCode = "";          //条码规则
    var scancodeWeb = "";
    var teamCode = "";        //班组编码
    var teamName = "";        //班组名称
    var shiftCode = "";       //班次编码
    var shiftName = "";       //班次名称
    var proddate = "";        //生产日期
    var barcode = "";//产品条码
    var pageParam = {};
    var arrSave = [];
    var isCheckPersonnelSkill = "";//是否开启人员上岗技能校验

    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;


    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //初始化查询仓库下拉框
    apiready = function () {

        //获取设备唯一号
        equipUniqueId = localStorage.getItem('equipUniqueId');
        $("#barcode").focus();
        idSelector = "barcode";
        //1:查询产线工位信息
        searchWorkCenterData();
        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');


    }




    //复检确认
    function confirm() {
        var barcode = $("#barcode").val();
        //物料号非空校验
        if (barcode == "" || barcode == null || barcode == undefined) {
            api.toast({
                msg: '产品条码不能为空！',
                duration: 3000
            });
            return;
        }
        var names = [];
        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }
        var picNames = JSON.parse(JSON.stringify(names));
        if (picNames == '' || picNames == null) {
            api.toast({
                msg: "请先上传复检确认图片！",
                duration: 3000
            });
            return
        }

        var empName = $("#empName").val();
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/repairPlanConfirm";
        var data = {
            values: {
                barcode: barcode, //产品条码
                workCellCode: workCellCode,
                lineCode: workCenterCode,
                shiftCode: shiftCode,
                shiftName: shiftName,
                proddate: proddate,
                equipUniqueId: equipUniqueId,
                empName: empName,
                picNames: picNames,
                un: un
            }
        };
        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    alert("返修复检确认成功")
                    $("#barcode").val("");
                    $api.html($api.byId("tbodyHtmlS"), "");
                    removeImg();
                } else {
                    alert(myobj.message);
                    $("#barcode").val("");
                    $api.html($api.byId("tbodyHtmlS"), "");
                    removeImg();
                }
            } else {

                $("#tm").val("");
                alert(JSON.stringify(err));
            }
        });
    }

    //查询数据
    function refresh() {
        //1:查询当前操作人员信息
        searchDutyPersonData();
    }





    //上岗
    function takeQuitPostClick() {
        if (opCode == null || opCode == "" || opCode == undefined) {
            api.toast({
                msg: "唯一号【" + equipUniqueId + "】未配置工序信息",
                duration: 3000
            });
            return;
        }
        api.openWin({
            name: "productionSglg",
            url: 'productionSglg.html',
            pageParam: pageParam,
        });
    }
    //构造传参map
    function createPageParam() {
        pageParam = {
            workCenterCode: workCenterCode,
            workCellCode: workCellCode,
            opCode: opCode,
            ruleCode: ruleCode,
            teamCode: teamCode,
            teamName: teamName,
            shiftCode: shiftCode,
            shiftName: shiftName,
            proddate: proddate,
            rootName: "recheckAndConfirm",
            name: "recheckAndConfirm",
            sgFlag: '0',//上岗标识：0刷卡，1勾选
            isCheckPersonnelSkill: isCheckPersonnelSkill
        }
    }


    //查询产线工位信息
    function searchWorkCenterData() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getOpCodeByUniCode";
        var data = {
            values: {
                clientCode: equipUniqueId,
                un: un,
            }
        };

        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                if (myobj.code == 0) {

                    //标题
                    //    document.getElementById("title").innerHTML = myobj.opCode + "压铸件";
                    workCenterCode = myobj.workCenterCode;
                    workCellCode = myobj.workCellCode;
                    opCode = myobj.opCode;
                    ruleCode = myobj.ruleCode;
                    isCheckPersonnelSkill = myobj.isCheckPersonnelSkill;

                    if (opCode != null && opCode != "") {

                        //1:查询当前操作人员信息
                        searchDutyPersonData();


                    }

                } else {
                    api.toast({
                        msg: myobj.msg,
                        duration: 3000
                    });
                }
            } else {
                alert("网络连接超时!")
            }
        });
    }



    //查询人员信息
    function searchDutyPersonData() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getProductionAssemblyTake";
        var data = {
            values: {
                workCenterCode: workCenterCode,
                opCode: opCode,
                workCellCode: workCellCode,
                un: un,
            }
        };
        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                console.log(myobj.code)

                if (myobj.code == 0) {
                    console.log(myobj.empName)
                    document.getElementById("empName").value = myobj.empName;
                    teamCode = myobj.teamCode;
                    teamName = myobj.teamName;
                    shiftCode = myobj.shiftCode;
                    shiftName = myobj.shiftName;
                    proddate = myobj.proddate;


                } else {
                    api.toast({
                        msg: myobj.msg,
                        duration: 3000
                    });

                    //清空人员信息
                    clear();
                }
                //5:构造参数
                createPageParam();
            } else {
                alert("网络连接超时!")
            }
        });
    }

    //清空人员上岗信息
    function clear() {
        document.getElementById("empName").innerHTML = "";
        teamCode = "";
        teamName = "";
        shiftCode = "";
        shiftName = "";
        proddate = "";
    }


    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            if (idSelector == 'barcode') {

                $("#barcode").val(ret);
                doSearch()


            }
        });
    }

    $("#barcode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {

            $("#barcode").val(sm);
            doSearch()
        }
    });


    //查询
    function doSearch() {
        var empName = $("#empName").val();
        if (empName == null || empName == "" || empName == undefined) {
            api.toast({
                msg: "未上岗,不允许操作",
                duration: 3000
            });
            return;
        }
        var un = localStorage.getItem('un');
        var probarcode = $("#barcode").val();
        if (probarcode == "" || probarcode == null || probarcode == undefined) {
            api.toast({
                msg: '条码不能为空！',
                duration: 3000
            });
            return;
        }
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/selectRepairPlan";
        var data = {
            values: {
                un: un,
                kpart_code: probarcode,
                ruleCode: workCenterCode,
                clientCode: equipUniqueId,
                opCode:opCode
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {
                    var list = eval(myobj.list);
                    var html = "";
                    for (var i = 0; i < list.length; i++) {
                        var ext04 = list[i].ext04 == '0' ? '线上返修' : '返修区返修';
                        var ext06 = list[i].ext06 == '0' ? '未确认' : '已确认';
                        var ext05 = list[i].ext05 == 'OK' ? '已确认' : '未确认';
                        var finish_flag = list[i].finish_flag == '0' ? '未确认' : '已确认';
                        html += "<li class='sortable ui-selectee ui-sortable'>";
                        html += "<ul class='aui-list aui-media-list ui-selectee'>";
                        html += "<li class='aui-list-item  ui-selectee'>";
                        html += "<div class='aui-media-list-item-inner ui-selectee'>";
                        html += "<div class='aui-list-item-inner ui-selectee'>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 50%;'>产品序列号：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].kpart_code + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 50%;'>产品物料编码：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].produ_code + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title'style='width: 50%;'>产品物料名称：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].produ_name + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 50%;'>返修工序：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].ext03 + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 50%;'>返回工序：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].re_op_code + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 50%;'>返修类别：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + ext04 + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 50%;'>返修确认结果：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + ext06 + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title' style='width: 80%;'>返修复检确认结果：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + ext05 + "</div>";
                        html += "</div>";
                        html += "<div class='aui-list-item-text ui-selectee' style='height: 35px;'>";
                        html += "<div class='aui-list-item-label ui-selectee list-tr-title'style='width: 80%;'>返修计划完成标识：</div>";
                        html += "<div class='aui-list-item-inner ui-selectee'>" + finish_flag + "</div>";
                        html += "</div>";

                        html += "</div>";
                        html += "</li>";
                        html += "</ul>";
                        html += "</li>";
                    }
                    $api.html($api.byId("tbodyHtmlS"), html);
                    //失败
                } else if (myobj.code == "1") {
                    $("#barcode").val("")

                    //清空表格数据
                    $api.html($api.byId("tbodyHtml"), "");
                    alert( myobj.message);
                }
            }
        });
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }

    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();
        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4  aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            if (ret.list) {
                                for (var i = 0; i < ret.list.length; i++) {
                                    var selectImg = ret.list[i];
                                    // 获取图片的路径
                                    var selectimgPath = selectImg.path;
                                    var selectimgThumbPath = selectImg.thumbPath;
                                    // 图片压缩
                                    imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                        var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;'  onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                            "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                        // 追加图片
                                        $("#addpic").before(showImgHtml);
                                        // ########################################  绑定长按事件 ########################
                                        addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                        // ################### 上传图片 #########################
                                        uploadFile(compressImg);
                                    });
                                }
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function (ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function (e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 为图片添加点击预览功能,排除添加按钮
    function lookImg(compressImg) {
        // 定义一个数组，存储需要预览的图片
        var browerImgs = [];
        // 调用图片预览函数
        browerImgs.push(compressImg);
        openImageBrowser(browerImgs);
    }

    //保存成功后，清除图片
    function removeImg() {
        var imgs = document.getElementsByTagName('img');
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var obj = $("#imgslist img[src='" + srcStr + "']").parent("li");
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            if ("add.jpg" != nameStr) {
                $(obj).remove();
            }
        }
    }



</script>

</html>